package com.feimt.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feimt.common.R;
import com.feimt.pojo.Employee;
import com.feimt.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/*
 * 1. 请求路径
 * 2. 请求方式
 * 3. 参数：格式json  @RequestBody    -- 前端会有一个拦截器参数一些处理
 *
 *  json {}  []                   @RequestBody
 *  ?k=v     post("xxx","id"=v)   @RequestParam  省略
 *  /xx/1111     /{id}           @PathVariable
 *
 * */
@RestController
@Slf4j
@RequestMapping("/employee")
@Api(tags = "员工管理模块")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session){
        log.info("employee={}",employee);

//        * 1. 密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
//        * 2. 根据密码查询用户是否存在
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(qw);

        if(one == null){
            log.info("用户名不存在");
            return R.error("用户名不存在");
        }

//        * 3. 比较密码
        if(!password.equals(one.getPassword())){
            log.info("密码错误");
            return R.error("密码错误");
        }
//        * 4. 判断是有禁用
        if(one.getStatus() == 0){
            log.info("用户被禁用");
            return R.error("用户被禁用");
        }

//        * 5. 存入会话session
        session.setAttribute("auth",one.getId());
//        * 6. 返回数据
        return R.success(one);
    }

    @ApiOperation("登出")
    @PostMapping("/logout")
    public R logout(HttpSession session){
        log.info("退出登录");
        session.removeAttribute("auth");
        return R.success("退出登录");
    }

    /*
    * 新增员工
    * */
    @ApiOperation("新增员工")
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        log.info("employee:{}",employee);
        // 1. 接收数据
        // 2. null 字段的默认处理
        // 2.1 密码初始化加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        // 2.2 创建时间修改时间 now当前时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        // 2.3 操作人 修改人 = 登录人
//        Long auth = (Long) session.getAttribute("auth");
//        employee.setCreateUser(auth);
//        employee.setUpdateUser(auth);
        // 2.4 设定默认状态
        employee.setStatus(1);

        // 3. 保存
        boolean flag = employeeService.save(employee);

        return flag?R.success("新增成功"):R.error("新增失败");
    }

    @ApiOperation("分页查询")
    @GetMapping("page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);
        //1. 构建分页条件
        Page<Employee> employeePage = new Page<>(page, pageSize);
        //2. 构建查询条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
//        qw.like(name!=null&&!"".equals(name),Employee::getName,name);
        qw.like(!StringUtils.isEmpty(name),Employee::getName,name);
        //3. 构建排序条件
        qw.orderByDesc(Employee::getUpdateTime);
        qw.orderByAsc(Employee::getName);
        //4. 查询
        employeeService.page(employeePage,qw);
        //5. 返回数据
        return R.success(employeePage);
    }

    /*
    * 员工信息修改
    * */
    @ApiOperation("员工信息修改")
    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
        System.err.println("web线程ID:"+Thread.currentThread().getId());
        log.info("修改employee:{}",employee);
        //1.公共字段处理
//        employee.setUpdateTime(LocalDateTime.now());
//        Long auth = (Long) session.getAttribute("auth");
//        employee.setUpdateUser(auth);
        //2.修改
        boolean flag = employeeService.updateById(employee);

        return flag?R.success("修改成功"):R.error("修改失败");
    }

    /*
    * 根据ID查询员工信息
    * */
    @ApiOperation("根据ID查询员工信息")
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        log.info("根据ID查询:{}",id);

        //1.查询
        Employee employee = employeeService.getById(id);

        return R.success(employee);
    }


}
